const formatTime = (d, sign) => {
  const date = new Date(d)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  // sign 如果0的话返回的是用/来拼接
  // sign 如果1的话返回的是用-来拼接
  return [year, month, day].map(formatNumber).join(['/', '-', ':'][sign]) + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const app = getApp()
const { getTime } = require('../api/geData.js')
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/** 列表处理函数 **/
const listSolve = list => {
  let solve = [],
    staObt = {}
  list.forEach((it) => {
    switch (it.status) {
      case "0":
        staObt = {
          staSrc: '/images/mine/weikaishi@2x.png',
          left: 'border-left:2px solid #CCCCCC',
          show: false
        }
        break;
      case "1":
        staObt = {
          staSrc: '/images/mine/ybm.png',
          left: 'border-left:2px solid #FF294C',
          show: false
        }
        break;
      case "2":
        staObt = {
          staSrc: '/images/mine/yfksj.png',
          left: 'border-left:2px solid #FF294C',
          show: false
        }
        break;
      case "3":
        staObt = {
          staSrc: '/images/mine/yipaiban@2x.png',
          left: 'border-left:2px solid #FFA422',
          show: false
        }
        break;
      case "4":
        staObt = {
          staSrc: '/images/mine/yipaiban@2x.png',
          left: 'border-left:2px solid #2E8EFF',
          show: true
        }
        break;
      case "5":
        staObt = {
          staSrc: '/images/mine/daikaiban@2x.png',
          left: 'border-left:2px solid #FFA422',
          show: true
        }
        break;
      case "6":
        staObt = {
          staSrc: '/images/mine/yikaiban@2x.png',
          left: 'border-left:2px solid #2E8EFF',
          show: true
        }
        break;
      case "7":
        staObt = {
          staSrc: '/images/mine/yijieke@2x.png',
          left: 'border-left:2px solid #CCCCCC',
          show: true
        }
        break;
    }
    Object.assign(it, staObt)
    solve.push(it)
  })
  return solve
}

// 查看消息栏有没有消息
const getNewsMsg = () => {
  wx.request({
    url: app.globalData.baseUrl + "/gmessage/findGmessageList" ,
    data: {
      telephone: wx.getStorageSync('userInfo').account,
      status: '',
      gmessageType: '0',
      from: '0'
    },
    method: "POST",
    header: {
      "Content-Type": "application/json"
    },
    success(res) {
      let data = res.data.data.gmessageList
      data.forEach(val => {
        if (val.status == "0") {
          app.setTabBarBadge('1')
        }
      })
    }
  })
}

// 获取系统时间
const getTimeFn = () => {
  getTime().then(res => {
    // res.currentTime = 1547087168000
    wx.setStorageSync('time', formatTime(res.currentTime, 1).split(' ')[0])
  })
}

// 处理日历回填的早 中 晚 
const formatDateDtate = val => {
  switch (val) {
    case '早':
      return 'top'
      break
    case '中':
      return 'middle'
      break
    case '晚':
      return 'bottom'
      break
      // 没有default
  }
}


// 分享过来统一函数
const  shareFn = () => {
  let share = wx.getStorageSync('share')
  let url = share.isShare && share.path || '../../grade/grade';
  wx.switchTab({
    url: url,
  })
}

// 消息推送
const sendForm = (formId, templateId, msgType, courseId, packId) => {
  // console.log(app)
  let url = '/wxmetal/metal',
    data = {
      // access_token:'',
      // touser: 'ogRh75ds3yPc94UzWdlkMLZ8pooo',
      touser: wx.getStorageSync('openid'),
      form_id: formId,
      template_id: templateId,
      page: '/pages/news/news',
      msgtype: msgType,
      courseid: courseId,
      packid: packId
    }
  wx.request({
    url: app.globalData.baseUrl + url,
    data: data,
    method: 'post',
    header: {
      'content-type': 'application/json'
    },
    success(res) {
      // console.log(res)
    },
    fail(err) {
      // console.log(err)
    }
  })
}

// 时间转化成时间戳
const changeTime = (data, time) => new Date(data+' '+time).getTime()

// 时间不吻合 不同意统一函数
const disagreeFn = (courseId) => {
  let that = this
  wx.showModal({
    title: '',
    content: '取消后，该课程将变为未开始状态，可在个人中心-我的课程中查看，确认取消',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    confirmColor: '#2A8EFF',
    success(e) {
      if (e.confirm) {

        wx.request({
          url: app.globalData.baseUrl + "/calendars/cancleIntent",
          method: "POST",
          data: {
            "stuId": wx.getStorageSync('userInfo').cluesOrStuId,
            "courseId": courseId,
          },
          header: {
            "Content-Type": "application/json	"
          },
          success(res){
            wx.navigateBack({
              url: '/pages/grade/grade',
            })
          }
        })

        
      }
    }

  })
}

// 格式化日期
const intDate = (self, fromDay, toDay) => {
  let platform;
  wx.getSystemInfo({
    success: function(res) {
      platform = res.platform
      // console.log(platform)
    },
  })
  let nowYear = fromDay.year,
    nowMonth = fromDay.month,
    nowDay = fromDay.day,
    nowTimeStamp = new Date(nowYear, nowMonth, nowDay).getTime(), // 课程时间段 开始时间的时间戳 用于后面的比较

    endDate = new Date(toDay.year, toDay.month, toDay.day), // 获取结束的日期
    endYM = new Date(endDate.getFullYear(), endDate.getMonth()), //获取结束月份
    endTimeStamp = endDate.getTime(), // 课程时间段 结束时间的时间戳 用于后面的比较

    dates = [];

  for (let i = nowMonth * 1; new Date(nowYear, i) <= endYM; i++) {
    let item = [];
    let monthDays = new Date(nowYear, i + 1, 0).getDate(); //获取该月天数
    for (let j = 1; j <= monthDays; j++) {
      let _year = new Date(nowYear, i).getFullYear(),
        _month = new Date(nowYear, i).getMonth() + 1,

        day = _year + '/' + _month + '/' + j,
        inDate = `${_year}-${_month}-${j}`,
        oDate = {}
      if (platform == 'ios') {
        inDate = `${_year}/${_month}/${j}`
      }
      oDate.week = new Date(inDate).getDay()
      oDate.month = _year + '年' + formatNumber(_month) + '月'
      oDate.orderTime = {
        top: false,
        middle: false,
        bottom: false
      }
      oDate.date = day.toString()
      oDate.choosed = false

      // 筛选出时间段  用inDate 标记  用时间戳来比较
      if (new Date(inDate).getTime() >= nowTimeStamp && new Date(inDate).getTime() <= endTimeStamp) {
        oDate.inDate = true
      }
      item.push(oDate)
    }
    dates.push(item)
  }
  // console.log(dates)
  let startDay = `${nowYear}/${nowMonth + 1}/${nowDay}`,
    endDay = `${endDate.getFullYear()}/${endDate.getMonth() + 1}/${endDate.getDate()}`;
  // console.log(dates)
  self.setData({
    dates,
    startDay,
    endDay
  })
}
module.exports = {
  formatTime: formatTime,
  listSolve: listSolve,
  formatNumber: formatNumber,
  formatDateDtate: formatDateDtate,
  sendForm: sendForm,
  getNewsMsg: getNewsMsg,
  intDate: intDate,
  changeTime: changeTime,
  getTimeFn: getTimeFn,
  disagreeFn: disagreeFn,
  shareFn: shareFn
}